public class Main {
    public static MySingleList.Node getIntersectionNode(MySingleList.Node headA , MySingleList.Node headB){
        // 先求链表的长度
       int lenA = 0;
       int lenB = 0;
       MySingleList.Node pl = headA;
       MySingleList.Node ps = headB;
       while(pl!=null){
           lenA++;
           pl = pl.next;
       }
       while(ps!=null){
           lenB++;
           ps = ps.next;
       }

       //要指回来
       pl = headA;
       ps = headB;

        int len = lenA - lenB; // 要看大小
        if(len<0){
            // lenA<lenB
            pl = headB;
            ps = headA;
            len = lenB - lenA;
        }
        // 这样写可以保证 len一定是一个正数
        // pl指向的链表一定是最长的 ， ps指向的链表一定是最短的


        while(len != 0){
            pl = pl.next;
            len--;
        } // 让最长的走差值步

        //然后再一起走
        while(pl!=ps){
            pl = pl.next;
            ps= ps.next;
        }

        if(pl==ps&&pl==null){
            return null;
        }

        //走到这的时候说明相等了
        return pl;
        //也可以直接返回pl不用判断是否为null
    }

    public static void main(String[] args) {
        MySingleList mySingleList = new MySingleList();
        mySingleList.createLink();
        mySingleList.display();
        System.out.println("====尾插====");
        mySingleList.addLast(10);
        mySingleList.addLast(20);
        mySingleList.addLast(30);
        mySingleList.display();
        //先将其变成环
        mySingleList.createLoop();
        boolean flg = mySingleList.hasCycle();
        System.out.println(flg);
        MySingleList.Node ret = mySingleList.FirstLoopExit();
        System.out.println(ret.val);
    }

    public static void main1(String[] args) {
        System.out.println("Hello world!");
        MySingleList mySingleList1 = new MySingleList();
        MySingleList mySingleList2 = new MySingleList();
        createCut(mySingleList1.head,mySingleList2.head);
        MySingleList.Node ret = getIntersectionNode(mySingleList1.head,mySingleList2.head);
        System.out.println(ret.val);
    }
    public static void createCut(MySingleList.Node headA,MySingleList.Node headB){
        headB.next.next = headA.next.next;
    }
}